package id.khairizalnetani.tugasakhir;

import java.util.ArrayList;
import java.util.List;
import id.khairizalnetani.tugasakhir.entity.Keterangan;
import id.khairizalnetani.tugasakhir.entity.Laporan;
import id.khairizalnetani.tugasakhir.entity.Siswa;
import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Halaman2UbahDataActivity extends RoboActivity implements OnClickListener
{
	// inisialisasi object layout
	@InjectView(R.id.tvFlightSkadronUbahData)
	TextView					tvFlightSkadron;
	@InjectView(R.id.tvPelaporUbahData)
	TextView					tvPelapor;
	@InjectView(R.id.tvIdPelaporUbahData)
	TextView					tvNoId;
	@InjectView(R.id.tvTanggalUbahData)
	TextView					tvTanggal;
	@InjectView(R.id.btnUbahDataHal2)
	Button						btnUbahData;

	@InjectView(R.id.rbApelPagiUbahData)
	RadioButton					rbApelPagi;
	@InjectView(R.id.rbApelSiangUbahData)
	RadioButton					rbApelSiang;
	@InjectView(R.id.rbApelMalamUbahData)
	RadioButton					rbApelMalam;

	@InjectView(R.id.etJumlahTotalKelasUbahData)
	EditText					etJumlahAnggotaKelas;
	@InjectView(R.id.etJumlahTidakHadirUbahData)
	EditText					etTidakHadir;
	@InjectView(R.id.etJumlahHadirUbahData)
	EditText					etHadir;

	// Dinas Dalam
	@InjectView(R.id.spIDDinasDalam1UbahData)
	Spinner						spIDDinasDalam1;
	@InjectView(R.id.spIDDinasDalam2UbahData)
	Spinner						spIDDinasDalam2;
	@InjectView(R.id.spIDDinasDalam3UbahData)
	Spinner						spIDDinasDalam3;
	@InjectView(R.id.spIDDinasDalam4UbahData)
	Spinner						spIDDinasDalam4;
	@InjectView(R.id.spIDDinasDalam5UbahData)
	Spinner						spIDDinasDalam5;

	// Dinas Luar
	@InjectView(R.id.spIDDinasLuar1UbahData)
	Spinner						spIDDinasLuar1;
	@InjectView(R.id.spIDDinasLuar2UbahData)
	Spinner						spIDDinasLuar2;
	@InjectView(R.id.spIDDinasLuar3UbahData)
	Spinner						spIDDinasLuar3;
	@InjectView(R.id.spIDDinasLuar4UbahData)
	Spinner						spIDDinasLuar4;
	@InjectView(R.id.spIDDinasLuar5UbahData)
	Spinner						spIDDinasLuar5;

	// Sakit
	@InjectView(R.id.spIDSakit1UbahData)
	Spinner						spIDSakit1;
	@InjectView(R.id.spIDSakit2UbahData)
	Spinner						spIDSakit2;
	@InjectView(R.id.spIDSakit3UbahData)
	Spinner						spIDSakit3;
	@InjectView(R.id.spIDSakit4UbahData)
	Spinner						spIDSakit4;
	@InjectView(R.id.spIDSakit5UbahData)
	Spinner						spIDSakit5;

	// RS -> Sakit
	@InjectView(R.id.spIDSakitRS1UbahData)
	Spinner						spIDSakitRS1;
	@InjectView(R.id.spIDSakitRS2UbahData)
	Spinner						spIDSakitRS2;
	@InjectView(R.id.spIDSakitRS3UbahData)
	Spinner						spIDSakitRS3;
	@InjectView(R.id.spIDSakitRS4UbahData)
	Spinner						spIDSakitRS4;
	@InjectView(R.id.spIDSakitRS5UbahData)
	Spinner						spIDSakitRS5;

	// berobat
	@InjectView(R.id.spIDBerobat1UbahData)
	Spinner						spIDBerobat1;
	@InjectView(R.id.spIDBerobat2UbahData)
	Spinner						spIDBerobat2;
	@InjectView(R.id.spIDBerobat3UbahData)
	Spinner						spIDBerobat3;
	@InjectView(R.id.spIDBerobat4UbahData)
	Spinner						spIDBerobat4;
	@InjectView(R.id.spIDBerobat5UbahData)
	Spinner						spIDBerobat5;

	// RS -> Berobat
	@InjectView(R.id.spIDBerobatRS1UbahData)
	Spinner						spIDBerobatRS1;
	@InjectView(R.id.spIDBerobatRS2UbahData)
	Spinner						spIDBerobatRS2;
	@InjectView(R.id.spIDBerobatRS3UbahData)
	Spinner						spIDBerobatRS3;
	@InjectView(R.id.spIDBerobatRS4UbahData)
	Spinner						spIDBerobatRS4;
	@InjectView(R.id.spIDBerobatRS5UbahData)
	Spinner						spIDBerobatRS5;

	// Izin
	@InjectView(R.id.spIDIzin1UbahData)
	Spinner						spIDIzin1;
	@InjectView(R.id.spIDIzin2UbahData)
	Spinner						spIDIzin2;
	@InjectView(R.id.spIDIzin3UbahData)
	Spinner						spIDIzin3;
	@InjectView(R.id.spIDIzin4UbahData)
	Spinner						spIDIzin4;
	@InjectView(R.id.spIDIzin5UbahData)
	Spinner						spIDIzin5;

	// TK
	@InjectView(R.id.spIDTK1UbahData)
	Spinner						spIDTK1;
	@InjectView(R.id.spIDTK2UbahData)
	Spinner						spIDTK2;
	@InjectView(R.id.spIDTK3UbahData)
	Spinner						spIDTK3;
	@InjectView(R.id.spIDTK4UbahData)
	Spinner						spIDTK4;
	@InjectView(R.id.spIDTK5UbahData)
	Spinner						spIDTK5;

	// kumpulan array untk spinner
	private Spinner[]			arrayDinasDalam;
	private Spinner[]			arrayDinasLuar;
	private Spinner[]			arraySakit;
	private Spinner[]			arrayRSSakit;
	private Spinner[]			arrayBerobat;
	private Spinner[]			arrayRSBerobat;
	private Spinner[]			arrayIzin;
	private Spinner[]			arrayTK;

	// deklarasi variable final apel
	private static final int	TXT_APEL_PAGI		= 0;
	private static final int	TXT_APEL_SIANG		= 1;
	private static final int	TXT_APEL_MALAM		= 2;

	private static final int	TXT_DINASDALAM		= 0;
	private static final int	TXT_DINASLUAR		= 1;
	private static final int	TXT_SAKIT			= 2;
	private static final int	TXT_BEROBAT			= 3;
	private static final int	TXT_IZIN			= 4;
	private static final int	TXT_TANPAKETERANGAN	= 5;

	// inisialisasi objek kelas dbadapter
	private DBAdapter			db;
	private long				id_report;

	// inisialisasi objek kelas laporan
	private Laporan				laporan;
	// inisialisasi objek kelas siswa
	private Siswa				siswa;
	private List<Siswa>			listSiswa;
	private List<String>		listNamaSiswa;
	private List<String>		listRS;

	private ProgressDialog		pDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_halaman2_ubah_data);

		btnUbahData.setOnClickListener(this);

		// instance class db adapter
		db = new DBAdapter(this);
		db.open();
		// mengambil data dari bundle yang di bawa oleh activity sebelumny
		Bundle bundle = getIntent().getExtras();
		// cek apakah bundle kosong atau tidak
		if (bundle != null)
		{
			// jika tidak kosong maka ambil data
			id_report = bundle.getLong(Halaman3.TAG_ID_REPORT);
		}

		// jalankan asynctask
		new AsyncTaskHalamanUbahData().execute();

		instanceArraySpinner();

		// fungsi untk penanganan perubahan teks..
		// untuk automatis hitung
		etTidakHadir.addTextChangedListener(new TextWatcher()
		{

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s)
			{
				if (etTidakHadir.getText().toString().equals(""))
				{
					// Jika tidak hadir kosong...
					// tidak melalukan apa2
				} else
				{
					// ambil data dari jumlah tidak hadir
					// kemudian hitung jumlah kelas - jumlah tidak hadir
					etHadir.setText("" + (laporan.getJumlah() - Integer.parseInt(etTidakHadir.getText().toString())));
				}

			}
		});

	}

	private void setSpinner()
	{
		listNamaSiswa = new ArrayList<String>();
		listNamaSiswa.add("ID SISWA");
		listRS = new ArrayList<String>();
		listRS.add("Rumah Sakit Tujuan");
		listRS.add("RSAU");
		listRS.add("RUSPAU");
		listRS.add("RSPAD");

		for (int i = 0; i < listSiswa.size(); i++)
		{
			listNamaSiswa.add(String.valueOf(listSiswa.get(i).getId()) + " - " + listSiswa.get(i).getNama());
		}

		ArrayAdapter<String> namaSiswaAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				listNamaSiswa);
		namaSiswaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		ArrayAdapter<String> namaRSAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				listRS);
		namaRSAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		for (int i = 0; i < 5; i++)
		{
			arrayDinasDalam[i].setAdapter(namaSiswaAdapter);
			arrayDinasLuar[i].setAdapter(namaSiswaAdapter);
			arraySakit[i].setAdapter(namaSiswaAdapter);
			arrayRSSakit[i].setAdapter(namaRSAdapter);
			arrayBerobat[i].setAdapter(namaSiswaAdapter);
			arrayRSBerobat[i].setAdapter(namaRSAdapter);
			arrayIzin[i].setAdapter(namaSiswaAdapter);
			arrayTK[i].setAdapter(namaSiswaAdapter);
		}

	}

	private void instanceArraySpinner()
	{
		arrayBerobat = new Spinner[]
		{
				spIDBerobat1, spIDBerobat2, spIDBerobat3, spIDBerobat4, spIDBerobat5
		};
		arrayRSBerobat = new Spinner[]
		{
				spIDBerobatRS1, spIDBerobatRS2, spIDBerobatRS3, spIDBerobatRS4, spIDBerobatRS5
		};
		arraySakit = new Spinner[]
		{
				spIDSakit1, spIDSakit2, spIDSakit3, spIDSakit4, spIDSakit5
		};
		arrayRSSakit = new Spinner[]
		{
				spIDSakitRS1, spIDSakitRS2, spIDSakitRS3, spIDSakitRS4, spIDSakitRS5
		};
		arrayDinasDalam = new Spinner[]
		{
				spIDDinasDalam1, spIDDinasDalam2, spIDDinasDalam3, spIDDinasDalam4, spIDDinasDalam5
		};
		arrayDinasLuar = new Spinner[]
		{
				spIDDinasLuar1, spIDDinasLuar2, spIDDinasLuar3, spIDDinasLuar4, spIDDinasLuar5
		};
		arrayIzin = new Spinner[]
		{
				spIDIzin1, spIDIzin2, spIDIzin3, spIDIzin4, spIDIzin5
		};
		arrayTK = new Spinner[]
		{
				spIDTK1, spIDTK2, spIDTK3, spIDTK4, spIDTK5
		};

	}

	// set tampilan berupa flight skadron, nama, id, dan data array
	private void setDataKeTampilan()
	{
		tvPelapor.setText(siswa.getNama());
		tvNoId.setText("" + siswa.getId());
		String teksSkadron = "";
		switch (siswa.getSkadron())
		{
			case 1:
				teksSkadron = "I";
				break;
			case 2:
				teksSkadron = "II";
				break;
			case 3:
				teksSkadron = "III";
				break;
			case 4:
				teksSkadron = "IV";
				break;
		}
		String teksFlight = "";
		switch (siswa.getFlight())
		{
			case 1:
				teksFlight = "I";
				break;
			case 2:
				teksFlight = "II";
				break;
			case 3:
				teksFlight = "III";
				break;
			case 4:
				teksFlight = "IV";
				break;
		}
		tvFlightSkadron.setText("Flight " + teksFlight + " Skadron " + teksSkadron);
		tvTanggal.setText(laporan.getTanggal());

		Utils.TRACE("jenis apel :" + laporan.getJenis_apel());
		switch (laporan.getJenis_apel())
		{
			case TXT_APEL_PAGI:
				rbApelPagi.setChecked(true);
				break;
			case TXT_APEL_SIANG:
				rbApelSiang.setChecked(true);
				break;
			case TXT_APEL_MALAM:
				rbApelMalam.setChecked(true);
				break;
		}

		etJumlahAnggotaKelas.setText("" + laporan.getJumlah());
		etTidakHadir.setText("" + laporan.getKurang());
		etHadir.setText("" + laporan.getHadir());

	}

	private boolean checkingSemua()
	{

		// cek jumlah yang tidak hadir apakah sudah diisi
		if (etTidakHadir.getText().toString().equals(""))
		{
			Toast.makeText(this, "Mohon isi jumlah tidak hadir", Toast.LENGTH_LONG).show();
			return true;
		}

		int jumlah = Integer.parseInt(etTidakHadir.getText().toString());
		int banding = getCountFromSpinner();

		if (jumlah != banding)
		{
			Toast.makeText(this, "Jumlah id diinputkan tidak sama dengan jumlah tidak hadir", Toast.LENGTH_LONG).show();
			return true;

		}

		if (checkRS())
		{
			Toast.makeText(this, "Cek rumah sakit tujuan untuk alasan sakit dan berobat", Toast.LENGTH_LONG).show();
			return true;
		}

		return false;
	}

	private int getCountFromSpinner()
	{
		int count = 0;
		for (int i = 0; i < 5; i++)
		{
			if (arrayDinasDalam[i].getSelectedItemPosition() != 0)
			{
				Utils.TRACE("tambah count Dinas Dalam");
				count++;
			}

			if (arrayDinasLuar[i].getSelectedItemPosition() != 0)
			{
				Utils.TRACE("tambah count Dinas Luar");
				count++;
			}

			if (arraySakit[i].getSelectedItemPosition() != 0)
			{
				Utils.TRACE("tambah count Sakit ");
				count++;
			}
			if (arrayBerobat[i].getSelectedItemPosition() != 0)
			{
				Utils.TRACE("tambah count Berobat ");
				count++;
			}
			if (arrayIzin[i].getSelectedItemPosition() != 0)
			{
				Utils.TRACE("tambah count Izin");
				count++;
			}
			if (arrayTK[i].getSelectedItemPosition() != 0)
			{
				Utils.TRACE("tambah count TK");
				count++;
			}

		}
		return count;

	}

	private int getRadioChecked()
	{
		if (rbApelMalam.isChecked())
		{
			return TXT_APEL_MALAM;
		} else if (rbApelPagi.isChecked())
		{
			return TXT_APEL_PAGI;
		} else if (rbApelSiang.isChecked())
		{
			return TXT_APEL_SIANG;
		}

		return 0;
	}

	private boolean checkRS()
	{
		for (int i = 0; i < 5; i++)
		{
			if (arraySakit[i].getSelectedItemPosition() != 0)
			{
				if (arrayRSSakit[i].getSelectedItemPosition() == 0)
				{
					return true;
				}

			}
			if (arrayBerobat[i].getSelectedItemPosition() != 0)
			{
				if (arrayRSBerobat[i].getSelectedItemPosition() == 0)
				{
					return true;
				}

			} else
			{
				return false;
			}

		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.halaman2_ubah_data, menu);
		return true;
	}

	private class AsyncTaskEditData extends AsyncTask<Void, Void, Void>
	{
		boolean	cek	= false;

		@Override
		protected Void doInBackground(Void... params)
		{
			// TODO Auto-generated method stub

			int jenisApel = getRadioChecked();
			int jumlahHadir = Integer.parseInt(etJumlahAnggotaKelas.getText().toString());
			int kurang = Integer.parseInt(etTidakHadir.getText().toString());
			int hadir = Integer.parseInt(etHadir.getText().toString());

			Laporan laporan = new Laporan();
			laporan.setId_report(id_report);
			laporan.setId_pelapor(siswa.getId());
			laporan.setJenis_apel(jenisApel);
			laporan.setTanggal(tvTanggal.getText().toString());
			laporan.setJumlah(jumlahHadir);
			laporan.setKurang(kurang);
			laporan.setHadir(hadir);

			// update laporan
			cek = db.updateLaporan(laporan);
			Utils.TRACE("Cek laporan " + cek);

			if (cek)
			{
				for (int i = 0; i < 5; i++)
				{
					if (arrayDinasDalam[i].getSelectedItemPosition() != 0)
					{

						Utils.TRACE("Create report Dinas Dalam");
						Utils.TRACE("Insert ke - " + (i + 1));
						db.createReportKet(new Keterangan(id_report,
								listSiswa.get(arrayDinasDalam[i].getSelectedItemPosition() - 1).getId(),
								TXT_DINASDALAM));
					}
					if (arrayDinasLuar[i].getSelectedItemPosition() != 0)
					{

						Utils.TRACE("Create report Dinas Luar");
						Utils.TRACE("Insert ke - " + (i + 1));
						db.createReportKet(new Keterangan(id_report, listSiswa
								.get(arrayDinasLuar[i].getSelectedItemPosition() - 1).getId(), TXT_DINASLUAR));
					}
					if (arraySakit[i].getSelectedItemPosition() != 0)
					{

						Utils.TRACE("Create report Sakit");
						Utils.TRACE("Insert ke - " + (i + 1));
						db.createReportSakit(new Keterangan(id_report, listSiswa
								.get(arraySakit[i].getSelectedItemPosition() - 1).getId(), TXT_SAKIT,
								arrayRSSakit[i]
										.getSelectedItem().toString()));
					}
					if (arrayBerobat[i].getSelectedItemPosition() != 0)
					{

						Utils.TRACE("Create report Berobat");
						Utils.TRACE("Insert ke - " + (i + 1));
						db.createReportSakit(new Keterangan(id_report, listSiswa
								.get(arrayBerobat[i].getSelectedItemPosition() - 1).getId(), TXT_BEROBAT,
								arrayRSBerobat[i]
										.getSelectedItem().toString()));
					}
					if (arrayIzin[i].getSelectedItemPosition() != 0)
					{

						Utils.TRACE("Create report Izin");
						Utils.TRACE("Insert ke - " + (i + 1));

						db.createReportKet(new Keterangan(id_report, listSiswa
								.get(arrayIzin[i].getSelectedItemPosition() - 1).getId(), TXT_IZIN));
					}
					if (arrayTK[i].getSelectedItemPosition() != 0)
					{

						Utils.TRACE("Create report TK");
						Utils.TRACE("Insert ke - " + (i + 1));
						db.createReportKet(new Keterangan(id_report, listSiswa
								.get(arrayTK[i].getSelectedItemPosition() - 1).getId(), TXT_TANPAKETERANGAN));
					}

				}

			} else
			{
				Toast.makeText(Halaman2UbahDataActivity.this, "Gagal udpate laporan", Toast.LENGTH_LONG).show();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.dismiss();

			// jika laporan berhasil diupdate maka pindah ke activity
			if (cek)
			{
				Bundle bundle = new Bundle();
				bundle.putInt("id", siswa.getId());
				bundle.putLong("id_report", id_report);

				Intent i = new Intent(Halaman2UbahDataActivity.this, Halaman3.class);
				i.putExtras(bundle);
				startActivity(i);
				Utils.TRACE("close db : ");
				db.close();

			}

		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if (pDialog == null)
				pDialog = new ProgressDialog(Halaman2UbahDataActivity.this);
			pDialog.setMessage("Loading...");
			pDialog.setCancelable(true);
			pDialog.show();
		}
	}

	private class AsyncTaskHalamanUbahData extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... params)
		{
			laporan = db.getReportById(id_report);
			siswa = db.getSiswaById(laporan.getId_pelapor());
			listSiswa = db
					.getAllSiswaBySkadronAndFlight(siswa.getFlight(), siswa.getSkadron(), laporan.getId_pelapor());
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub

			pDialog.dismiss();

			setDataKeTampilan();
			setSpinner();
			super.onPostExecute(result);

		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();
			if (pDialog == null)
				pDialog = new ProgressDialog(Halaman2UbahDataActivity.this);
			pDialog.setMessage("Loading...");
			pDialog.setCancelable(true);
			pDialog.show();
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			// jalankan asynctask ubah data
			case R.id.btnUbahDataHal2:
				if (!checkingSemua())
				{
					new AsyncTaskEditData().execute();
				}
				break;

		}

	}

}
